//
//  AddrChooserViewModel.m
//  EnvironmentalProtection
//
//  Created by HCreater on 2018/10/23.
//  Copyright © 2018年 HCreater. All rights reserved.
//

#import "AddrChooserViewModel.h"

#import "MultTitleItemViewModel.h"

#import <ReactiveCocoa/RACErrorSignal.h>

@interface AddrChooserViewModel () <CLLocationManagerDelegate>

@property (nonatomic, strong) CLLocationManager* locationManager;

/// 请求数据的命令
@property (nonatomic, readwrite, strong) RACCommand *requestDataCommand;

@end

@implementation AddrChooserViewModel

#pragma mark - Ovrride
- (void)initialize
{
    [super initialize];
    
    DataManager* dm = [DataManager sharedDataManager];
    
    self.locationCityData = nil;
    
    self.isShowCountryChoose = YES;
    
    self.lastPage = 999;
    
    /// 不需要再viewDidLoad后加载数据
    self.shouldRequestRemoteDataOnViewDidLoad = YES;
    
    /// 允许下拉刷新
    self.shouldPullDownToRefresh = NO;
    /// 允许上拉加载
    self.shouldPullUpToLoadMore = NO;
    
    self.locationManager = [[CLLocationManager alloc] init];
    self.locationManager.delegate = self;
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    self.locationManager.distanceFilter = 100.0f;
    
    self.currentProvinceDatas = dm.addrData.datas;
    
    @weakify(self)
    
    self.didSelectCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(NSIndexPath *indexPath)
                             {
                                 @strongify(self);
                                 
                                 bool isOverSelected = NO;
                                 
                                 if (self.searchProvinceDatas && self.searchProvinceDatas.count > indexPath.row)
                                 {
                                     isOverSelected = YES;
                                     
                                     self.chooseBlock(self.searchProvinceDatas[indexPath.row]);
                                 }
                                 else
                                 {
                                     ProvinceListData* choosePData = self.currentProvinceDatas[indexPath.row];
                                     
                                     if (choosePData.datas.count > 0)
                                     {
                                         if (choosePData.datas.count == 1)
                                         {
                                             isOverSelected = YES;
                                             
                                             self.chooseBlock(choosePData.datas[0]);
                                         }
                                         else
                                         {
                                             [self _nextLv:choosePData];
                                         }
                                     }
                                     else
                                     {
                                         isOverSelected = YES;
                                         
                                         self.chooseBlock(choosePData);
                                     }
                                 }
                                 
                                 return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
                                     [subscriber sendNext:@(isOverSelected)];
                                     [subscriber sendCompleted];
                                     
                                     return nil;
                                 }];
                             }];
    
    self.chooseLocationCmd = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(NSIndexPath *indexPath)
                              {
                                  @strongify(self);
                                  
                                  bool isSuc = NO;
                                  
                                  if (self.locationCityData)
                                  {
                                      isSuc = YES;
                                      
                                      self.chooseBlock(self.locationCityData);
                                  }
                                  
                                  return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber)
                                  {
                                      [subscriber sendNext:@(isSuc)];
                                      [subscriber sendCompleted];
                                      
                                      return nil;
                                  }];
                              }];
    
    self.relocationCmd = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input)
                          {
                              @strongify(self);
                              
                              self.locationCityData = nil;
                              
                              @weakify(self)
                              return [[[self requestLocationSignal] doNext:^(id x)
                                      {
                                          @strongify(self);
                                          
                                          CLPlacemark* place = x;
                                          
                                          NSString* strAddr = @"";
                                          
#if TARGET_IPHONE_SIMULATOR
                                          //iPhone Simulator
                                          strAddr = @"汕头市";
#else
                                          strAddr = place.locality;
#endif
                                          
                                          self.locationCityData = [self _findPData:strAddr];
                                      }] doError:^(NSError *error)
                                      {
                                          @strongify(self);
                                          
#if TARGET_IPHONE_SIMULATOR
                                          //iPhone Simulator
                                          NSString* strAddr = @"汕头市";
                                          
                                          self.locationCityData = [self _findPData:strAddr];
#endif
                                      }];
                          }];
}

- (RACSignal *)requestRemoteDataSignalWithPage:(NSUInteger)page
{
    @weakify(self);
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        
        @strongify(self);
        
        NSArray* curDatas = (self.searchProvinceDatas!=nil && self.searchProvinceDatas.count>0) ? self.searchProvinceDatas : self.currentProvinceDatas;
        
        NSArray *viewModels = [curDatas.rac_sequence map:^MultTitleItemViewModel *(ProvinceListData * provinceData) {
            MultTitleItemViewModel *itemViewModel = [[MultTitleItemViewModel alloc] initWithData:@{@"Title":provinceData.name, @"Info":provinceData} cellHeight:44.0f];
            
            return itemViewModel;
        }].array;
        
        self.dataSource = viewModels;
        
        [subscriber sendNext:nil];
        [subscriber sendCompleted];
        
        return nil;
    }];
}

//用rac定位 返回信号内容是有个布尔值：用户是否授权
- (RACSignal *)autoriedSignal
{
    //判断是否授权
    if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined) {
        //没有授权就提示用户授权
        [self.locationManager requestWhenInUseAuthorization];
        //创建用户授权结果的信号
        return [[self rac_signalForSelector:@selector(locationManager:didChangeAuthorizationStatus:) fromProtocol:@protocol(CLLocationManagerDelegate)] map:^id(id value) {
            return @([value[1] integerValue] == kCLAuthorizationStatusAuthorizedWhenInUse );
        }];
    }
    return [RACSignal return:@([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedWhenInUse)];
}

- (RACSignal*)requestLocationSignal
{
    //autoriedSignal判断是否授权
    return [[[self autoriedSignal] filter:^BOOL(id value) {
        //过滤 如果授权就往下
        return [value boolValue];
    }] flattenMap:^RACStream *(id value) {
        //授权过的 跟踪定位信息
        return [[[[[[[self rac_signalForSelector:@selector(locationManager:didUpdateLocations:) fromProtocol:@protocol(CLLocationManagerDelegate)] map:^id(id value) {
            //取代理方法的第二个值
            return value[1];
        }] merge:[[self rac_signalForSelector:@selector(locationManager:didFailWithError:) fromProtocol:@protocol(CLLocationManagerDelegate)] map:^id(id value) {
            //定位失败返回错误信息
            return [RACSignal error:value[1]];
        }]] take:1] initially:^{
            //信号开始前做什么
            [self.locationManager startUpdatingLocation];
        }] finally:^{
            //信号结束后做什么
            [self.locationManager stopUpdatingLocation];
        }] flattenMap:^RACStream *(id value) {
            
            if ([value isKindOfClass:[RACErrorSignal class]])
                return value;
            
            CLLocation *location = [value firstObject];
            return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
                //反编码获取地理信息
                CLGeocoder *geocoder = [[CLGeocoder alloc]init];
                [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
                    if (error) {
                        [subscriber sendError:error];
                    }else{
                        [subscriber sendNext:[placemarks firstObject]];
                        [subscriber sendCompleted];
                    }
                }];
                return [RACDisposable disposableWithBlock:^{
                    
                }];
            }];
        }];
    }];
    
}

#pragma mark -- 定位
//- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
//{
//    switch (status)
//    {
//        case kCLAuthorizationStatusNotDetermined:
//        {
//            if ([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)])
//            {
//                [self.locationManager requestWhenInUseAuthorization];
//
//            }
//        }
//            break;
//
//        default:
//            break;
//    }
//}
//
//- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
//{
//    CLLocation *newLocation = locations[0];
//
//    CLLocationCoordinate2D oldCoordinate = newLocation.coordinate;
//
//    NSLog(@"旧的经度：%f,旧的纬度：%f",oldCoordinate.longitude,oldCoordinate.latitude);
//
//    [manager stopUpdatingLocation];
//
//    @weakify(self)
//    CLGeocoder *geocoder = [[CLGeocoder alloc]init];
//    [geocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray<CLPlacemark *> *_Nullable placemarks, NSError * _Nullable error)
//     {
//         @strongify(self)
//
//         for (CLPlacemark *place in placemarks)
//         {
//             NSLog(@"name,%@",place.name);                      // 位置名
//             NSLog(@"thoroughfare,%@",place.thoroughfare);      // 街道
//             NSLog(@"subThoroughfare,%@",place.subThoroughfare);// 子街道
//             NSLog(@"subLocality,%@",place.subLocality);        // 区
//             NSLog(@"locality,%@",place.locality);              // 市
//             NSLog(@"locality,%@",place.administrativeArea);    // 省
//             NSLog(@"country,%@",place.country);                // 国家
//
//             NSString* strAddr = @"";
//
//#if TARGET_IPHONE_SIMULATOR
//             //iPhone Simulator
//             strAddr = @"广东省";
//#else
//             strAddr = place.administrativeArea；
//#endif
//
//             DataManager* dMgr = [DataManager sharedDataManager];
//             for (ProvinceData* curPData in dMgr.addrData.datas)
//             {
//                 if ([curPData.provinceName containsString:strAddr])
//                 {
//                     self.locationProvinceData = curPData;
//
//                     break;
//                 }
//             }
//         }
//     }];
//}

#pragma mark - 功能
- (ProvinceListData*)_findPData:(NSString*)strAddr
{
    DataManager* dMgr = [DataManager sharedDataManager];
    for (ProvinceListData* curPPData in dMgr.addrData.datas)
    {
        if (curPPData.datas.count > 0)
        {
            for (ProvinceListData* curSPData in curPPData.datas)
            {
                if ([curSPData.name isEqualToString:strAddr])
                {
                    return curSPData;
                }
            }
        }
        else if ([curPPData.name isEqualToString:strAddr])
        {
            return curPPData;
        }
    }
    
    return nil;
}

- (ProvinceListData*)_findPDataByID:(NSString*)areaID
{
    DataManager* dMgr = [DataManager sharedDataManager];
    for (ProvinceListData* curPPData in dMgr.addrData.datas)
    {
        if (curPPData.datas.count > 0)
        {
            for (ProvinceListData* curSPData in curPPData.datas)
            {
                if ([curSPData.areaID isEqualToString:areaID])
                {
                    return curSPData;
                }
            }
        }
        else if ([curPPData.areaID isEqualToString:areaID])
        {
            return curPPData;
        }
    }
    
    return nil;
}

- (void)_nextLv:(ProvinceListData*)parentData
{
    self.currentProvinceDatas = parentData.datas;
    
    [self.requestRemoteDataCommand execute:0];
}

- (BOOL)try2Pop
{
    bool result = YES;
    
    if (self.searchProvinceDatas!=nil && self.searchProvinceDatas.count>0)
    {
        result = NO;
        
        self.searchProvinceDatas = nil;
        
        [self.requestRemoteDataCommand execute:0];
    }
    else if (self.currentProvinceDatas.count > 0)
    {
        ProvinceListData* pdata = self.currentProvinceDatas[0];
        
        if ([pdata.parentID integerValue] > 0)
        {
            result = NO;
            
            DataManager* dm = [DataManager sharedDataManager];
            
            self.currentProvinceDatas = dm.addrData.datas;
            
            [self.requestRemoteDataCommand execute:0];
        }
    }
    
    return result;
}

- (void)searchCityByName:(NSString*)cityName
{
    NSMutableArray* findPDatas = [NSMutableArray array];
    
    DataManager* dMgr = [DataManager sharedDataManager];
    for (ProvinceListData* curPPData in dMgr.addrData.datas)
    {
        if (curPPData.datas.count > 0)
        {
            for (ProvinceListData* curSPData in curPPData.datas)
            {
                if ([curSPData.name containsString:cityName])
                {
                    [findPDatas addObject:curSPData];
                }
            }
        }
    }
    
    if (findPDatas.count > 0)
    {
        self.searchProvinceDatas = findPDatas;
        
        [self.requestRemoteDataCommand execute:0];
    }
}

@end
